import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { createError } from './errorHandler';
import { getStoragePath, ensureDirectoryExists, generateUniqueFilename } from '../config/storage';

// 配置头像存储
const avatarStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    // 头像使用专门的目录，不按日期组织
    const avatarDir = path.join('uploads', 'avatars');
    ensureDirectoryExists(avatarDir);
    cb(null, avatarDir);
  },
  filename: (req, file, cb) => {
    const userId = (req as any).user?.id;
    const filename = generateUniqueFilename(file.originalname, userId);
    // 添加avatar前缀
    const avatarFilename = `avatar-${filename}`;
    cb(null, avatarFilename);
  }
});

// 头像文件过滤器
const avatarFileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 只允许图片类型
  const allowedImageTypes = [
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/gif',
    'image/webp'
  ];

  if (allowedImageTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(createError('只支持 JPEG、PNG、GIF、WebP 格式的图片文件', 400));
  }
};

export const avatarUploadMiddleware = multer({
  storage: avatarStorage,
  fileFilter: avatarFileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB 限制
    files: 1 // 只允许单个文件
  },
});